<template>
  <div class="cmt-banner">
      <h1>发表评论</h1>
      <hr>
      <textarea placeholder="最多输入120个字" maxlength="120" v-model="content"></textarea>
      <mt-button type="primary" size="large" @click="setComment">发表评论</mt-button>
      <div class="cmt-content" v-for="(item,i) in comList" :key="i">
          <p>第{{i+1}}楼&nbsp;&nbsp;{{item.user_name}}&nbsp;&nbsp;{{item.add_time | comment()}}</p>
          <!-- 判断如果内容为空，则代替数据，有则用原先的数据 -->
          <p>{{item.content==='undefined'||item.content===''?'无内容':item.content}}</p>
      </div>
      <mt-button type="danger" size="large" plain class="more" @click="getMore">加载更多</mt-button>
  </div>
</template>
<script>
import { Toast } from 'mint-ui';
export default {
  data() {
    return {
      content:'',
      pageindex: 1,
      comList: []
    };
  },
  props: ["id"],
  created() {
    this.getComments();
  },
  methods: {
      //首次获取数据
    getComments() {
      this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageindex)
        .then(results => {
          if (results.body.status == 0) {
            this.comList = results.body.message;
            console.log(this.comList)
          } else {
            Toast("请检查网络！");
          }
        });
    },
    //点击加载获取数据，原先数据加上新获取的数据
    getMore(){
        this.pageindex++;
        this.$http
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageindex)
        .then(results => {
          if (results.body.status == 0) {
            // this.comList = results.body.message;
            // this.comList = this.comList.push.apply(null,results.body.message)
            //es6语法合并数组
            this.comList = [...this.comList,...results.body.message];
            if(results.body.message.length<10){
                Toast('无更多内容')
            }
          } else {
            Toast("请检查网络！");
          }
        });
    },
    setComment(){
        this.$http.post('api/postcomment/'+this.id,{artid:this.id,content:this.content},{emulateJSON:true}).then((results)=>{
            if(results.body.status===0){

                this.pageindex=1;
                this.getComments();
                this.content ='';
            }
        })
    }
  }
};
</script>
<style lang="scss" scoped>
.cmt-banner {
  h1 {
    font-size: 20px;
  }
  textarea {
    font-size: 14px;
    color: rgb(35, 120, 216);
  }
  .cmt-content {
    p {
      margin-bottom: 0;
      &:nth-child(1) {
        font-size: 12px;
        background-color: #ddd;
        line-height: 30px;
        margin-top: 10px;
        text-indent: 1em;
        border-radius: 10px;
      }
      &:nth-child(2) {
        font-size: 14px;
        line-height: 40px;
        text-indent: 2em;
        color: #000;
      }
    }
  }
  .more{
      margin-bottom: 10px;
  }
}
</style>
